// 公共复制剪贴板
const uiCopy = str => {
  let copyDom = document.createElement('div');
  copyDom.innerText = str;
  copyDom.style.position = 'absolute';
  copyDom.style.top = '0px';
  copyDom.style.right = '-9999px';
  document.body.appendChild(copyDom);
  //创建选中范围
  let range = document.createRange();
  range.selectNode(copyDom);
  //移除剪切板中内容
  window.getSelection().removeAllRanges();
  //添加新的内容到剪切板
  window.getSelection().addRange(range);
  //复制
  let successful = document.execCommand('copy');
  copyDom.parentNode.removeChild(copyDom);
  try {
    uiMsg(successful ? '复制成功!' : '复制失败，请手动复制内容', null, successful ? 'success' : 'error');
  } catch (err) { }
};

// 下载base64格式的图片
const uiDownloadImg = (data, fileName) => {
  var link = document.createElement('a');
  link.href = data;
  link.download = fileName;
  link.click();
};

//定义一个require方法
const myRequire = (imgPath) => {
  try {
    const handlePath = imgPath.replace('@', '..');
    return new URL(handlePath, import.meta.url).href;
  } catch (error) {
    console.warn(error);
  }
}

//base64转file
function base64toFile(base64Data, filename = 'file') {
  const arr = base64Data.split(',')
  const names = arr[0].match(/:(.*?);/)
  const mime = names ? names[1] : ''
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], `${filename}`, {
      type: mime,
  })
}

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

export { uiCopy, uiDownloadImg, myRequire, base64toFile, getBase64 };